var G_windowTitle;
var form;
var G_id;
$(document).ready(function () {
  initLayui();
  initTable();
  
});

function initLayui() {
  layui.use(['form'], function () {
    form = layui.form;

    form.on('submit(filter)', function (data) {
      initTable();
      return false;
    });

    form.on('submit(search)', function (data) {
      initTable();
      return false;
    });

    form.on('submit(save)', function (data) {
      var params = {
        id: G_windowTitle == '新增' ? null : G_id,
        name: data.field.name,
        account: data.field.account,
        roleId: data.field.roleId,
        phone: data.field.phone,
      };
      save(params);
      return false;
    });

    form.on('switch(updateStatus)', function (data) {
      AjaxRequest(
        '/user/status/update',
        callBack,
        {
          id: data.value,
          type: data.elem.checked ? 1 : 2,
        },
        'post'
      );

      function callBack(result) {
        if (result.status == 200) {
          layer.msg('已成功' + (data.elem.checked ? '启用！' : '停用！'));
        }
      }
    });
  });
}

// 新增编辑弹窗
function showWindow(title, res) {
  layer.open({
    type: 1,
    title: title,
    skin: 'default-class',
    area: ['4.5rem', 'auto'],
    // shade: false,
    move: false,
    closeBtn: 2,
    id: 1, //设置该值后，不管是什么类型的层，都只允许同时弹出一个。
    content: `<form class="layui-form" lay-filter="saveForm" style="margin: .3rem;">
                <div class="layui-form-item">
                  <label class="layui-form-label">姓名</label>
                  <div class="layui-input-block">
                    <input type="text" name="name" autocomplete="off" class="layui-input" lay-verify="required">
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">账号</label>
                  <div class="layui-input-block">
                    <input type="text" name="account" autocomplete="off" class="layui-input" lay-verify="required">
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">角色</label>
                  <div class="layui-input-block">
                    <select id="roleId" name="roleId" lay-verify="required"></select>
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">电话</label>
                  <div class="layui-input-block">
                    <input type="text" name="phone" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-form-item form-btn" style="text-align:center">
                  <div class="layui-input-block" style="margin-left: 0;">
                    <button class="layui-btn" lay-submit lay-filter="save">保存</button>
                  </div>
                </div>
              </form>`, //这里content是一个普通的String
    success: function (layero, index) {
      initRoleSelect();
      G_windowTitle = title;
      setTimeout(() => {
        if (title == '编辑') {
          G_id = res.id;
          //给表单赋值
          form.val('saveForm', {
            name: res.name,
            account: res.account,
            roleId: res.roleId,
            phone: res.phone,
          });
        }
      }, 100);
    },
  });
}

function initRoleSelect() {
  AjaxRequest('/role/select', callBack);

  function callBack(result) {
    if (result.status == 200) {
      var data = result.result;
      var str = '<option value="">请选择</option>';
      $.each(data, function (i, val) {
        str += `<option value="${val.id}">${val.name}</option>`;
      });
      $('#roleId').empty().append(str);
      form.render();
    }
  }
}

// 保存表单
function save(data) {
  AjaxRequest('/user/save', callBack, data, 'post');

  function callBack(result) {
    if (result.status == 200) {
      initTable();
      layer.closeAll();
      layer.msg('保存成功！');
    } else {
      layer.msg('保存失败！');
    }
  }
}

function initTable() {
  layui.use('table', function () {
    var table = layui.table;
    var height = $('.search-content').innerHeight() - 20;

    //第一个实例
    table.render({
      title: '',
      height: height,
      text: {
        none: '暂无数据',
      },
      elem: '#table',
      skin: 'nob',
      headers: {
        SessionId: JSON.parse(localStorage.getItem('userInfo')).sessionId,
      },
      url: ajaxPrefix() + '/user/list',
      where: {
        name: $('#search-name').val(),
      },
      parseData: function (res) {
        //res 即为原始返回的数据
        return {
          code: res.status == 200 ? 0 : 1, //解析接口状态
          msg: res.message, //解析提示文本
          count: res.result?res.result.total:0, //解析数据长度
          data: res.result?res.result.data:[], //解析数据列表
        };
      },
      request: {
        pageName: 'pageNum', //页码的参数名称，默认：page
        limitName: 'pageSize', //每页数据量的参数名，默认：limit
      },
      page: {
        //开启分页
        limit: 10,
      },
      cols: [
        [
          //表头
          {
            field: 'name',
            title: '姓名',
            align: 'center',
          },
          {
            field: 'account',
            title: '账号',
            align: 'center',
          },
          {
            field: 'phone',
            title: '电话',
            align: 'center',
          },
          {
            field: 'roleName',
            title: '角色名称',
            align: 'center',
          },
          {
            field: '',
            title: '状态',
            align: 'center',
            templet: $('#switch-status'),
          },
          {
            field: '',
            title: '操作',
            align: 'center',
            width: 200,
            templet: function (d) {
              let res = JSON.stringify(d);
              return `<div class="table-tool">
                        <div onclick='showWindow("编辑",${res})'>
                          <img src="../static/img/edit.png">编辑
                        </div>
                        <div onclick='showDelWindow(${res})'>
                          <img src="../static/img/delete.png">删除
                        </div>
                      </div>`;
            },
          },
        ],
      ],
    });
  });
}

function showDelWindow(res) {
  layer.confirm(
    '确认是否删除?',
    {
      btn: ['确认', '取消'], //按钮
    },
    function () {
      AjaxRequest('/user/delete?id=' + res.id, callBack);

      function callBack(result) {
        if (result.status == 200) {
          initTable();
          layer.closeAll();
          layer.msg('删除成功!');
        }
      }
    }
  );
}
